package com.hw

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.rdd.RDD

/**
 * 4、统计总分大于平均分的学生
 */
object Demo4DaYuAgeScore {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setMaster("local")
    conf.setAppName("Filter")
    val sc = new SparkContext(conf)
    val scoreRDD: RDD[String] = sc.textFile("hadoop_code/src/data/score.txt")

    //取出每个学生的总分
    val sumScore: RDD[(String, Int)] = scoreRDD.map(
      line => {
        val split: Array[String] = line.split(",")
        (split(0), split(2).toInt)
      }
    ).reduceByKey((x, y) => x + y)

    val avgScore: Double = sumScore.map(
      kv => kv._2
    ).sum() / sumScore.count()

    val filter: RDD[(String, Int)] = sumScore.filter(
      kv => kv._2.toDouble > avgScore
    )

    val joinRDD: RDD[(String, (Int, Int))] = scoreRDD.map(
      line => {
        val split: Array[String] = line.split(",")
        (split(0), split(2).toInt)
      }
    ).join(filter)

    val resRDD: RDD[String] = joinRDD.map {
      case (id: String, (score: Int, allScore: Int)) =>
        s"$id\t$score"
    }

    resRDD.foreach(println)





  }

}
